﻿/*!
 *  @brief     串口通信-同步通信
 *  @details
 *  @author    YZG
 *  @version   1.0
 *  @date      20190728
 *  @warning
 *  @copyright NanJing RenGu.
 *  @note
 */
#ifndef SERIALPORTTHREAD_H
#define SERIALPORTTHREAD_H

#include "common_global.h"

#include <QObject>
#include <QSerialPort>

#define SERIALPORT_REPLY_TIMEOUT   3000

namespace Common {

	class COMMONSHARED_EXPORT SerialPort : public QObject
	{
		Q_OBJECT
	public:
		explicit SerialPort(QObject *parent = Q_NULLPTR);
		~SerialPort();

	public:
		/**
		 * @brief getSerialPort 获取串口指针
		 * @return
		 */
		QSerialPort * getSerialPort();

		/**
		 * @brief	open  打开串口
		 * @param	portName 串口名称
		 * @param	baudRate 波特率
		 * @param	dataBits 数据位
		 * @param	parity
		 * @param	stopBits 停止位
		 * @param	flowControl 流控
		 * @return
		 */
		bool open(const QString portName, const QSerialPort::BaudRate baudRate = QSerialPort::Baud9600,	const QSerialPort::DataBits dataBits = QSerialPort::Data8,
			const QSerialPort::Parity parity = QSerialPort::NoParity, const QSerialPort::StopBits stopBits = QSerialPort::OneStop, const QSerialPort::FlowControl flowControl = QSerialPort::NoFlowControl);

		/**
		 * @brief	close 关闭串口
		 * @return
		 */
		void close();

		/**
		 * @brief	isOpen 判断串口是否打开
		 * @return
		 */
		bool isOpen();

		/**
		 * @brief	clear 清除串口的数据
		 * @return
		 */
		bool clear();

		/**
		 * @brief	sendSerialMsg 发送串口消息
		 * @param	buff 写入的消息
		 * @return
		 */
		bool sendSerialMsg(const QByteArray buff);

		/**
		 * @brief	recvSerialMsg 接收串口消息
		 * @param	buff  接收的消息
		 * @param	replyTime 等待时间
		 * @return
		 */
		bool recvSerialMsg(QByteArray & buff, const int replyTime = SERIALPORT_REPLY_TIMEOUT);

		/**
		 * @brief	sendAndReceiveSerialMsg 发送与接收串口消息
		 * @param	sendMsg 待发送的消息
		 * @param	recvMsg 返回接收的消息
		 * @param	replyTime 回复等待时间
		 * @return
		 */
		bool sendAndReceiveSerialMsg(const QByteArray sendMsg, QByteArray &recvMsg, const int replyTime = SERIALPORT_REPLY_TIMEOUT);

	Q_SIGNALS:
		/**
		 * @brief signalSerialError 发送串口异常消息
		 * @param strError
		 */
		void signalSerialError(QString strError);

	private Q_SLOTS:
		/**
		* @brief slotReceiveErrorOccurred
		* @param error
		*/
		void slotReceiveErrorOccurred(QSerialPort::SerialPortError error);

	private:
		QSerialPort * m_serialPort;         // 串口操作类
	};

} //namespace Common

#endif // SERIALPORTTHREAD_H
